package com.lancoo.answer.view.fragment.composition.alternative;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lancoo.answer.R;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.util.SoftInputUtils;
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils;

import java.util.List;

/**
 * Created by pengmi on 2021/12/8 11:52
 * Description:二选一作文题作答fragmnet
 */
public class CompositionAlternativeAnswerFragment extends Fragment {

    private Child child;
    private static final String TAG = "CompositionAnswerFragme";
    private int currentAnswerItemIndex=-1;
    private int kindIndex;
    private int queseIndex;
    private int smallQueseIndex;
    public long subClickTime;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ev_fragment_composition_alternative_answer_layout, container, false);
    }


    public static Fragment loadChildFragment(int kindIndex, int queseIndex, int smallQueseIndex){

        CompositionAlternativeAnswerFragment queseFragment=new CompositionAlternativeAnswerFragment();
        Bundle mBundle=new Bundle();
        mBundle.putInt("kindIndex",kindIndex);
        mBundle.putInt("queseIndex",queseIndex);
        mBundle.putInt("smallQueseIndex",smallQueseIndex);
        queseFragment.setArguments(mBundle);
        return queseFragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    private void initView(View view){
        Log.e(TAG,"initView"+(child==null));
        if(getArguments()==null){
            return;
        }
        kindIndex = getArguments().getInt("kindIndex");
        queseIndex = getArguments().getInt("queseIndex");
        smallQueseIndex = getArguments().getInt("smallQueseIndex");
        if(ConstantBean.Companion.getConstantExamBean()==null){
            return;
        }
        List<Type> typeList = ConstantBean.Companion.getConstantExamBean().getTypeList();
        if(typeList==null||kindIndex>=typeList.size()){
            return;
        }
        Type type = typeList.get(kindIndex);
        List<Ques> quesList = type.getQuesList();
        if(quesList==null||quesList.size()<=queseIndex){
            return;
        }
        Ques ques = quesList.get(queseIndex);
        List<Child> childList = ques.getChildList();
        if(childList==null||childList.size()<=smallQueseIndex){
            return;
        }
        child = childList.get(smallQueseIndex);
        RecyclerView recyclerview = view.findViewById(R.id.recycler_view);
        recyclerview.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL,false));
        AlternativeAdapter mAdapter=new AlternativeAdapter(child);
        currentAnswerItemIndex=child.getSelectedItemIndex();
        mAdapter.setOnAlternativeChoiceCallBack(new AlternativeAdapter.OnAlternativeChoiceCallBack() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onChoiceItem(int position) {
                super.onChoiceItem(position);
                if(System.currentTimeMillis()-subClickTime<200){
                    return;
                }
                subClickTime=System.currentTimeMillis();

                if(child.getSelectedItemIndex()==position){
                    return;
                }
                showSwitchAnswerTypeDialog(position,mAdapter);


            }
        });
        recyclerview.setAdapter(mAdapter);
        currentAnswerItemIndex=child.getSelectedItemIndex();
        loadAnswerMethod(child.getSelectedItemIndex());
    }

    @SuppressLint("NotifyDataSetChanged")
    private void showSwitchAnswerTypeDialog(final int choicePosition, AlternativeAdapter mAdapter ){


        if(currentAnswerItemIndex==choicePosition||getContext()==null||getActivity()==null){
            return;
        }
        SoftInputUtils.hideSoftInput(getActivity());
        SharedPreferences sp=getContext().getSharedPreferences(AnswerConstant.SP_ANSWER_NAME,Context.MODE_PRIVATE);
        boolean isAgain=sp.getBoolean(AnswerConstant.SP_COMPOSITION_ALTERNATIVE,false);
        if(isAgain){
            child.setSelectedItemIndex(choicePosition);
            mAdapter.notifyDataSetChanged();
            loadAnswerMethod(choicePosition);
            return;
        }
        View inflate=LayoutInflater.from(getContext()).inflate(R.layout.ev_dialog_switch_answer_type,null);
        AlertDialog.Builder builder=new AlertDialog.Builder(getContext(),R.style.ev_dialogStyle);
        builder.setView(inflate);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        if(window==null){
            return;
        }
        WindowManager.LayoutParams attributes = window.getAttributes();
        TextView tv_content=inflate.findViewById(R.id.tv_content);
        tv_content.setText(R.string.ev_composition_alternative);
        int width = getContext().getResources().getDisplayMetrics().widthPixels;
        int px280 = (int)getContext().getResources().getDisplayMetrics().density*280;
        attributes.width=Math.min(width*280/375,px280);
        alertDialog.getWindow().setAttributes(attributes);

        inflate.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            if(System.currentTimeMillis()-subClickTime<200){
                return;
            }
            subClickTime=System.currentTimeMillis();
            alertDialog.dismiss();
            SharedPreferences.Editor edit = sp.edit();
            edit.putBoolean(AnswerConstant.SP_COMPOSITION_ALTERNATIVE,true);
            edit.apply();
            child.setSelectedItemIndex(choicePosition);
            mAdapter.notifyDataSetChanged();
            loadAnswerMethod(choicePosition);
        });
        inflate.findViewById(R.id.tv_sure).setOnClickListener(v -> {
            if(System.currentTimeMillis()-subClickTime<200){
                return;
            }
            subClickTime=System.currentTimeMillis();
            alertDialog.dismiss();
            child.setSelectedItemIndex(choicePosition);
            mAdapter.notifyDataSetChanged();
            loadAnswerMethod(choicePosition);
        });


    }




    private void loadAnswerMethod(int itemIndex){
        Log.e("subcom","loadAnswerMethod itemIndex:"+itemIndex);
        FragmentManager fragmentManager = getChildFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment= getChildFragmentManager().findFragmentByTag(itemIndex+"");//getFragmentManager()
        Fragment lastFragment= getChildFragmentManager().findFragmentByTag(currentAnswerItemIndex+"");//getFragmentManager()
        if(lastFragment!=null){
            FragmentCommunicationUtils.closeAllMediaPlay(lastFragment);
            fragmentTransaction.hide(lastFragment);
        }
        if(getActivity()!=null)
            SoftInputUtils.hideSoftInput(getActivity());
        if(fragment==null){
            fragment=SubCompositionAnswerFragment.loadChildFragment(kindIndex,queseIndex,smallQueseIndex,itemIndex);
            fragmentTransaction.add(R.id.framelayout_composition_alternative,fragment,itemIndex+"");
        }else{
            fragmentTransaction.show(fragment);
        }
        fragmentTransaction.commitAllowingStateLoss();
        currentAnswerItemIndex=itemIndex;
    }

}
